<?php


namespace App\Http\Controllers\Admin;

use App\Exceptions\ApiErrorException;
use App\Exceptions\ApiException;
use App\Models\AuthGroup;
use App\Models\NewAdmin;
use App\Services\AuthService;
use App\Services\Base\PaginateService;
use App\Services\CommonService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class BaseController extends BaseVerifyController
{
    protected $users;
    protected $userGroup;
    protected $page;
    protected $pageSize;

    //过滤验证 [目录\controller@action]
    protected $filterAction = [
        'Admin\LoginController@login',
        'Admin\MarketActivityController@info',
    ];

    public function __construct(Request $request)
    {
        parent::__construct($request);
        if (AuthService::checkFilter(request()->route()->action['controller'], $this->filterAction)) {
            $userToken = $request->header("Authorization");
            if (!$userToken) {
                throw new ApiErrorException('请登录', '接口缺少Token');
            }
            $cacheUser = Redis::get($userToken);
            if (!$cacheUser) {
                throw new ApiException('登录过期', CommonService::HTTP_CODE_NOT_LOGIN);
            }

            $user = json_decode($cacheUser, true);
            if (!$user) {
                throw new ApiErrorException('请登录', 'token json decode 失败');
            }

            $adminModel = NewAdmin::query()->find($user['id']);
            if (!$adminModel) {
                throw new ApiErrorException('请登录', "管理员(ID={$user['id']})不存在");
            }
            AuthService::getInstance()->setAdmin($adminModel);

            if ($adminModel['is_delete'] == CommonService::IS_DELETE_YES) {
                throw new ApiException('账号不存在', CommonService::HTTP_CODE_FAIL);
            }
            if ($adminModel['status'] == CommonService::USER_STATUS_NOT) {
                throw new ApiException('账号已冻结', CommonService::HTTP_CODE_FAIL);
            }
            $authGroup = AuthGroup::where(['id' => $adminModel['role_id'], 'is_delete' => CommonService::IS_DELETE_NOT, 'status' => CommonService::USER_STATUS_YES])->first();
            if ($authGroup) {
                if (!AuthService::checkClassAction($authGroup['rules'])) {
                    throw new ApiException('无权限', CommonService::HTTP_CODE_FAIL);
                }
                $this->userGroup = $authGroup;
                $this->users = $adminModel;
            }
        }

        if (method_exists($this, '_init')) {
            $this->_init();
        }

        $this->page = PaginateService::getInstance()->getPage();
        $this->pageSize = PaginateService::getInstance()->getPageSize();
    }

    public function _init()
    {

    }
}
